package cdc.cs.service;

import cdc.cs.common.HttpWithAuthService;
import cdc.cs.config.ODataConfig;
import cdc.cs.entity.BusinessPartnersVO;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: ODataPartnerService
 * @Description: TODO
 * @Author: kevin
 * @Date: 2020/5/28 15:19
 * @Version: 1.0
 */
@Service
@Slf4j
public class ODataPartnerService {
    private List<BusinessPartnersVO> partnersVOList;

    /**
     * 统计合作伙伴总数
     * @return
     */
    public Integer partnerGetAll() {
        String result = null;
        int count = 2;
        while (count > 0) {
            try {
                result = HttpWithAuthService.getService(ODataConfig.sourcePartner + "/$count");
            } catch (IOException e) {
                log.error("获取Partner总数网络异常，异常信息为:{}", e.getMessage());
            }
            if (StringUtils.isEmpty(result)) {
                count--;
            } else {
                break;
            }
        }
        return Integer.valueOf(result);
    }

    /**
     * 分页查询合作伙伴
     * @return
     */
    public List<BusinessPartnersVO> partnerPagination(Integer num) {
        String result = null;
        int count = 2;
        List<BusinessPartnersVO> list = null;
        while (count > 0) {
            try {
                int top = 5;
                int skip = (num-1)*5;
                StringBuilder url = new StringBuilder(ODataConfig.sourcePartner);
                url.append("?$format=json&")
                        .append("$top=")
                        .append(top)
                        .append("&$skip=")
                        .append(skip);
                result = HttpWithAuthService.getService(url.toString());
            } catch (IOException e) {
                log.error("获取Partner总数网络异常，异常信息为:{}，地址为:{}", e.getMessage(), ODataConfig.sourcePartner);
            }
            if (StringUtils.isEmpty(result)) {
                count--;
            } else {
                list = parsePartnerJson(result);
                break;
            }

        }

        return list;
    }

    /**
     * 解析合作伙伴的数据
     * @param response
     * @return
     */
    private List<BusinessPartnersVO> parsePartnerJson(String response) {
        List<BusinessPartnersVO> list = new ArrayList<>();
        JSONObject obj = (JSONObject) JSONObject.parse(response);
        JSONObject d = (JSONObject) obj.get("d");
        JSONArray results = d.getJSONArray("results");
        if (results.size() > 0) {
            for (int i = 0; i < results.size(); i++) {
                BusinessPartnersVO partnersVO = new BusinessPartnersVO();
                JSONObject object = results.getJSONObject(i);
                partnersVO.setBusinessPartner(object.getString("BusinessPartner"));
                partnersVO.setBusinessPartnerCategory(object.getString("BusinessPartnerCategory"));
                partnersVO.setBusinessPartnerGrouping(object.getString("BusinessPartnerGrouping"));
                partnersVO.setOrganizationBPName1(object.getString("OrganizationBPName1"));
                partnersVO.setFormOfAddress(object.getString("FormOfAddress"));

                JSONObject address = (JSONObject) object.get("to_BusinessPartnerAddress");
                JSONObject address1 = (JSONObject) address.get("__deferred");
                String addressString = address1.getString("uri");
                partnersVO.setToAddress(addressString+"?$format=json");

                JSONObject bank = (JSONObject) object.get("to_BusinessPartnerBank");
                JSONObject bank1 = (JSONObject) bank.get("__deferred");
                String bankString = bank1.getString("uri");
                partnersVO.setToBank(bankString+"?$format=json");

                JSONObject role = (JSONObject) object.get("to_BusinessPartnerRole");
                JSONObject role1 = (JSONObject) role.get("__deferred");
                String roleString = role1.getString("uri");
                partnersVO.setToRole(roleString+"?$format=json");

                list.add(partnersVO);
            }
        }
        this.partnersVOList = list;
        return list;
    }

    /**
     * 数据转换
     * @param partnersVO
     * @return
     */
    public JSONObject dataChange(BusinessPartnersVO partnersVO) {
        JSONObject result = new JSONObject();
        result.put("BusinessPartner", partnersVO.getBusinessPartner());
        result.put("BusinessPartnerCategory", partnersVO.getBusinessPartnerCategory());
        result.put("BusinessPartnerGrouping", partnersVO.getBusinessPartnerGrouping());
        result.put("FormOfAddress", partnersVO.getFormOfAddress());
        result.put("OrganizationBPName1", partnersVO.getOrganizationBPName1());
        result.put("ToAddress", partnersVO.getToAddress());
        result.put("ToBank", partnersVO.getToBank());
        result.put("ToRole", partnersVO.getToRole());
        return result;
    }

    public boolean savePartner(BusinessPartnersVO partnersVO) {
        JSONObject jsonObject = dataChange(partnersVO);
        int count = 2;
        boolean flag = false;
        while (count > 0) {
            try {
                HttpWithAuthService.postService(ODataConfig.targetPartner, jsonObject);
                flag = true;
            } catch (IOException e) {
                log.error("保存Partner出现异常，未保存数据为:{}，地址为:{}", jsonObject, ODataConfig.targetPartner);
            }
            if (flag) {
                break;
            } else {
                count--;
            }
        }
        return flag;
    }

    /**
     * 查询目标系统
     * @param partner
     */
    public boolean queryTarget(BusinessPartnersVO partner) {
        int count = 2;
        boolean flag = false;
        String result = null;
        String url1 = null;
        while (count > 0) {
            try {
                StringBuilder url = new StringBuilder(ODataConfig.targetPartner);
                url.append("(BusinessPartner='")
                        .append(partner.getBusinessPartner())
                        .append("',BusinessPartnerCategory='")
                        .append(partner.getBusinessPartnerCategory())
                        .append("',BusinessPartnerGrouping='")
                        .append(partner.getBusinessPartnerGrouping())
                        .append("',OrganizationBPName1='")
                        .append(partner.getOrganizationBPName1())
                        .append("')?$format=json");
                url1 = url.toString();
                result = HttpWithAuthService.getService(url.toString());
            } catch (Exception e) {
                log.error("获取TargetPartner总数网络异常，数据信息为:{}，地址为:{}", partner, url1);
            }
            if (StringUtils.isEmpty(result)) {
                count--;
            } else if (result.contains("error")){
                flag = false;
                break;
            } else {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 删除合作伙伴
     * @param partnersVO
     */
    public void deletePartner(BusinessPartnersVO partnersVO) {
        int count = 2;
        boolean flag = false;
        while (count > 0) {
            try {
                StringBuilder url = new StringBuilder(ODataConfig.targetPartner);
                url.append("('")
                        .append(partnersVO.getBusinessPartner())
                        .append("')");
                HttpWithAuthService.deleteService(url.toString());
                flag = true;
            } catch (IOException e) {
                log.error("删除TargetPartner异常，异常信息为:{}", e.getMessage());
            }
            if (flag) {
                break;
            } else {
                count--;
            }
        }
    }
}
